package com.chenxin.wms.process.inbound.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chenxin.common.constant.WmsConstants;
import com.chenxin.common.core.domain.ProcResult;
import com.chenxin.common.utils.StringUtils;
import com.chenxin.wms.domain.IbMasterEntity;
import com.chenxin.wms.domain.ModuleSerial;
import com.chenxin.wms.mapper.IbMasterMapper;
import com.chenxin.wms.process.inbound.IInBoundProcess;
import com.chenxin.wms.service.IModuleSerialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class InBoundProcessImpl implements IInBoundProcess {
    @Autowired
    private IbMasterMapper ibMasterMapper;

    @Autowired
    private IModuleSerialService moduleSerialService;

    @Override
    public ProcResult procWmsInBoundMasterInsert(IbMasterEntity ibMasterEntity) {
        if (ibMasterEntity == null) {
            return ProcResult.error("ibMaster_insert_err#001", "待写入的入库信息不能为空");
        }
        String ibMasterType = ibMasterEntity.getIbMasterType();
        String supplierNo = ibMasterEntity.getSupplierNo();
        if (StringUtils.isBlank(ibMasterType)) {
            return ProcResult.error("ibMaster_insert_err#002", "入库类型不能为空");
        }

        // 获取入库单号
        ModuleSerial moduleSerial = moduleSerialService.selectModuleSerialByCode(WmsConstants.IB_MODULE_CODE);
        if (StringUtils.isNull(moduleSerial)) {
            return ProcResult.error("ibMaster_insert_err#003", "入库单序列码[IB_MASTER_NO]未在[wms_module_serial]中配置");
        }

        String ibMasterNo = moduleSerialService.getSerialNo(moduleSerial);
        // 校验单号是否存在
        QueryWrapper<IbMasterEntity> ibMasterNoQuery = new QueryWrapper<>();
        ibMasterNoQuery.lambda().eq(IbMasterEntity::getIbMasterNo, ibMasterNo);
        Long count = ibMasterMapper.selectCount(ibMasterNoQuery);
        if (count > 0) {
            return ProcResult.error("ibMaster_insert_err#003", "入库单号【" + ibMasterNo + "】已存在，请重新生成");
        }
        // 写入入库单号
        ibMasterEntity.setIbMasterNo(ibMasterNo);
        int rows = ibMasterMapper.insert(ibMasterEntity);
        if (rows == 0) {
            return ProcResult.error("ibMaster_insert_err#004", "入库单【" + ibMasterNo + "】写入失败");
        }

        return ProcResult.success("成功写入入库单,相关单号【" + ibMasterNo + "】");
    }
}
